import { WechatyBuilder } from "wechaty";
import { sendAiMessage } from "./plugins/chatAi/chatAi";
const wechaty = WechatyBuilder.build(); // get a Wechaty instance
const roomIdList = [
  "@@ace64d15e977583800c3501dd085fb2f22210d8b2594eb0211c36509edb2d176",
  "@@44edf7519afb218a04d97a8c49705ffc1b3e558df8c681936b241ef8959ca766",
];
let checkGroupList: any[] = [];
let groups: any[] = [];
const onMessage = async (message: any) => {
  const { payload } = message;
  const { text } = payload;
  console.log(JSON.stringify(message));

  console.log(JSON.stringify(wechaty.Room));
  const room = message.room(); // 获取群聊实例

  if (room) {
    const roomName = await room.topic(); // 获取群名称
    const contact = message.from(); // 消息发送者
    console.log(`Message from room: ${roomName}, sender: ${contact.name()}`);
    const text = message.text();
    console.log(text);
    if (text.startsWith("@🇨🇳")) {
      const msg = text.replace("@🇨🇳", "");

      sendAiMessage(msg)
        .then(async(res) => {
          await room.say(res);
        })
        .catch(async(err) => {
          await room.say("很抱歉，我出错了");
        });
      // 主动回复群聊中的消息
      // if (message.text() === 'hello') {
      //   await room.say('Hello everyone in the group!')
      // }
      // await room.say('你好啊')
    }

    // 自动回复消息
  }
};

wechaty
  .on("scan", (qrcode, status) =>
    console.log(
      `Scan QR Code to login: ${status}\nhttps://wechaty.js.org/qrcode/${encodeURIComponent(
        qrcode
      )}`
    )
  )
  .on("login", (user) => console.log(`User ${user} logged in`))
  .on("message", async (message) => await onMessage(message));

wechaty.on("ready", async () => {
  const roomList = await wechaty.Room.findAll();
  checkGroupList = [];
  for (let index = 0; index < roomList.length; index++) {
    let room = roomList[index];
    let groupTopic = await room.topic();
    if (groups.includes(groupTopic)) {
      let roomItem = {
        topic: groupTopic,
        obj: room,
        time: "",
      };
      checkGroupList.push(roomItem);
    }
  }
  console.log("群列表");
  console.log(JSON.stringify(checkGroupList));

  console.log(`Total ${roomList.length} rooms found`);
});

wechaty.start();
